<template>
  <div>
    <div class="">
      <parser v-if="startParser"
              :key="parserKey"
              :form-model="formModel"
              :label-form-model="labelFormModel"
              :form-conf="formConf" @next="nextPage" @prev="prevPage" @submit="submitForm"
      />

        </div>
    </div>
</template>

<script>

import Parser from '@/components/DuoJuHe/Form/parser/Parser'
import {dbDataConvertForItemJson,pageShowHandle,checkAddNumberByItemType} from '@/utils/form/utils/convert'
import {getExpression} from '@/utils/form/utils/expression'
import _ from 'lodash'
import {queryFormProjectDetailsResByProjectId } from '@/api/form/formProject'
import {queryFormProjectLogicPageResByProjectId } from '@/api/form/formProjectLogic'
export default {
    components: {
        Parser
    },
    props: {
        projectConfig: {
            projectId: '',
            showBtns: true
        }
    },
    data() {
        return {
            logicItemMap:undefined,
            logicShowTriggerRule: {},
            startParser: false,
            formModel: {},
            labelFormModel: {},
            projectTheme: {
                headImage: '',
                logoImage: '',
                backgroundImg:'',
                showTitle: true,
                showDescribe: true
            },
            parserKey: +new Date(),
            // 每页数据
            perPageFields: {},
            formConf: {
                fields: [],
                logicShowRule: {},
                projectId: '',
                projectKind: 1,
                __methods__: {},
                formRef: 'elForm',
                formModel: 'formData',
                labelFormModel: 'labelFormData',
                size: 'small',
                labelPosition: 'top',
                labelWidth: 100,
                formRules: 'rules',
                gutter: 15,
                disabled: false,
                span: 24,
                formBtns: true,
                resetBtn: false,
                resetBtnColor: '#909399',
                resetBtnText: '重置',
                submitBtnText: '提交',
                submitBtnColor: '#409EFF',
                showNumber: false,
                unFocusedComponentBorder: true
            }
        }
    },
    computed: {},
    watch: {},
    created() {
        if (this.projectConfig && this.projectConfig.projectId) {
            this.formConf.projectId = this.projectConfig.projectId
        } else if (this.$route.query.key) {
            // 不存去路由中尝试获取 iframe
            this.formConf.projectId = this.$route.query.key
        }
        this.formConf.size = window.innerWidth < 480 ? 'medium' : 'small'
    },
    async mounted() {
      //beg
      let logicItemList = []
      // 处理逻辑表单
      let res = await this.queryLogicItemList()
      logicItemList = res.data
      let logicItemMap = new Map()
      logicItemList.forEach(item => {
        logicItemMap.set(item.formItemId, item)
        this.logicShowTriggerHandle(item)
      })
      queryFormProjectDetailsResByProjectId({"projectId":this.formConf.projectId}).then(res => {
        if (res.data) {
          let data = res.data
          let serialNumber = 1
          let fields = data.formProjectItemResList.map(item => {
            let projectItem = dbDataConvertForItemJson(item)
            projectItem.serialNumber = serialNumber
            projectItem.logicShow = !logicItemMap.get(projectItem.formItemId)
            if (checkAddNumberByItemType(item.type)){
              serialNumber++
            }
            return projectItem
          })
          //处理分页数据
          this.perPageFields = pageShowHandle(fields)

          if (_.keys(this.perPageFields).length != 0) {
            this.formConf.fields = _.get(this.perPageFields, 1)
            this.formConf.formBtns = false
          } else {
            this.formConf.fields = fields
          }
          if (data.formProjectRes) {
            let formProjectRes = data.formProjectRes
            this.formConf.title = formProjectRes.projectName
            this.formConf.description = formProjectRes.description
          }
          this.formConf.logicShowRule = this.logicShowTriggerRule
          // 主题数据
          if (data.formProjectStyleRes) {
            let formProjectStyleRes = data.formProjectStyleRes
            let {showNumber} = formProjectStyleRes
            if (showNumber) this.formConf.showNumber = showNumber
          }
          this.startParser = true
        }
      })
      //end
    },
    methods: {
        /**
       * 处理逻辑显示数据
       */
        logicShowTriggerHandle(logicItem) {
            if (!logicItem) {
                return
            }
            // 建立触发关系 该字段值发生变化时 哪些问题需要进行逻辑判断 确定是否显示
            logicItem.conditionList.forEach(item => {
                if (Object.keys(item).length === 0) {
                    return
                }
                let rules = this.logicShowTriggerRule[item.formItemId]
                if (!rules) {
                    rules = new Array()
                }
                rules.push({
                    // 触发的字段
                    triggerFormItemId: logicItem.formItemId,
                    logicExpression: getExpression(logicItem.conditionList, logicItem.expression)
                })
                this.logicShowTriggerRule[item.formItemId] = rules
            })
        },
      // 统一处理axios请求
      queryLogicItemList() {
        return new Promise((resolve, reject) => {
          queryFormProjectLogicPageResByProjectId({"projectId":this.formConf.projectId}).then(res => {
            resolve(res)
            }
          ).catch(err => {
            reject(err)
          })
        })
      },
        prevPage(params) {
            this.switchPage(params.page - 1, params)
        },
        nextPage(params) {
            this.switchPage(params.page + 1, params)
        },
        switchPage(page, params) {
            let {labelFormModel, formModel} = params
            this.formModel = formModel
            this.labelFormModel = labelFormModel
            this.formConf.formBtns = _.keys(this.perPageFields).length == page
            this.formConf.fields = _.get(this.perPageFields, page)
            this.parserKey = +new Date()
        },
        submitForm(data) {
          this.$emit('submit', data);
        }
    }
}
</script>

<style lang="scss">
.project-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
  background-repeat: repeat;
  background-color: rgba(229, 239, 247, 0.87);
}
.project-form .describe-html img{
  max-width: 780px;
  margin: 0px;
}

.project-body::-webkit-scrollbar {
  width: 0 !important;
  background: transparent;
}

.project-body {
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
}

.logo-img {
  max-height: 120px;
}

.submit-btn-form-item {
  text-align: center;
}

.submit-btn-form-item button {
  width: 20%;
}

@media screen and (max-width: 750px) {
  .project-form {
    margin: 0;
    width: 100% !important;
    background-color: white;
  }
  .logo-img {
    max-height: 2.94rem;
  }
  .submit-btn-form-item {
    text-align: center;
  }
  .submit-btn-form-item button {
    width: 80%;
  }
  .project-form .describe-html img{
    width: 95vw!important;
  }
}
</style>
